package com.jysz.certificate.web.action.cm.batchAdd;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.jysz.certificate.action.AbstractBaseAction;
import com.jysz.certificate.persistence.enums.CertificationType;
import com.jysz.certificate.persistence.enums.CopyOfCertificationImporting;
import com.jysz.certificate.persistence.enums.WorkflowOperateType;
import com.jysz.certificate.persistence.enums.WorkflowState;
import com.jysz.certificate.persistence.enums.WorkflowType;
import com.jysz.certificate.persistence.enums.applyAdd.ApplyAddType;
import com.jysz.certificate.persistence.model.cm.Certification;
import com.jysz.certificate.persistence.model.cm.applyAdd.ApplyCer;
import com.jysz.certificate.persistence.model.cm.applyAdd.ApplyCerDTO;
import com.jysz.certificate.persistence.model.cm.applyAdd.ApplyCerList;
import com.jysz.certificate.persistence.model.system.Financial;
import com.jysz.certificate.persistence.model.system.Organization;
import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.persistence.model.workflow.Workflow;
import com.jysz.certificate.service.CommonService;
import com.jysz.certificate.service.cm.CertificationService;
import com.jysz.certificate.service.cm.applyCer.ApplyCerListService;
import com.jysz.certificate.service.cm.applyCer.ApplyCerService;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.service.workflow.WorkflowService;
import com.jysz.certificate.utils.DateUtil;

@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/cm/batchAdd")
public class BatchAddAction extends AbstractBaseAction {

	/**
	 * 合格证批量补入
	 */
	private static final long serialVersionUID = 1L;
	
	@Resource
	private WorkflowService workflowService;
	@Resource
	private CertificationService certificationService;
	@Resource
	private OrganizationService organizationService;
	@Resource
	private ShopService shopService;// 销售店Service
	@Resource
	private ApplyCerService applyCerService;
	@Resource
	private ApplyCerListService applyCerListService;
	
	private Date applyDate;
	
	private List<Shop> shops;
	private ApplyCer applyCer;
	private Shop shop;
	private ApplyCerList cerF;
	private Financial financial;
	
	private ApplyCerDTO applyCerDTO;
	private String shopName;
	
	private Long shopId;
	private Long id;
	private Long applyCerListid;
	private Long[] applyIds;
	private Boolean mark;
	private String msg;
	
	
	
	@Action(INDEX)
	public String index(){
		if(StringUtils.isNotBlank(shopName)){
			if(applyCerDTO != null){
				applyCerDTO.setNameShop(shopName);
			}else{
				applyCerDTO = new ApplyCerDTO();
				applyCerDTO.setNameShop(shopName);
			}
		}
		setPage(applyCerService.findPage(applyCerDTO, getCurrentPage(),  getPageSize()));
		return INDEX;
	}
	
	/**
	 * 提交申请单
	 * @return
	 */
	@Action(ADD)
	public String add(){
		applyCer = applyCerService.find(id);
		
		String error = this.valCertificates(applyCer.getApplyCerLists());
		
		if(StringUtils.isNotBlank(error)){
			setFailPopMessage("提交失败:<br/>" + error);
			return SHOW_MSG_PAGE;
//			setRedirectUrl("");
		}
		
		applyCer.setState(ApplyAddType.SUBMITED);
		if(applyCer.getApplyCerLists().size() != 0){
			applyCer.setApplyDate(new Date());
			for(ApplyCerList applyCerList : applyCer.getApplyCerLists()){
				applyCerList.setState("待审核");
			}
		}else{
			setRedirectUrl("seleteOnApply.do?currentPage=${currentPage}&id=" + applyCer.getId() + "&shopId=" + applyCer.getShop().getId());
			setFailPopMessage("请添加合格证后再提交申请单。。");
			return SHOW_MSG_PAGE;
		}
		
		applyCerService.save(applyCer);
		
		Workflow w = workflowService.find(WorkflowType.ADDLIST, id);
		if(w != null){//判断是否存在该流程！
			workflowService.audit(getUser(), w, WorkflowState.SUBMITED, WorkflowOperateType.SUBMIT, "退回再提交");
		}else{
			workflowService.addWorkflow(getUser(), id, WorkflowState.SUBMITED, WorkflowType.ADDLIST, ApplyCer.class,"批量补录审核流程" );
		}
	
		
		setSuccessPopMessage("更新数据成功");
		setRedirectUrl("index.do");
		return SHOW_MSG_PAGE;
	}
	
	@Action(CREATE)
	public String create(){
		return null;
	}
	
	@Action(DELETE)
	public String delete(){
		applyCerService.destory(id);
		workflowService.destory(id, WorkflowType.ADDLIST);
		setSuccessPopMessage("删除数据成功");
		setRedirectUrl("index.do?currentPage="+getCurrentPage(),"applyCerDTO",applyCerDTO);
		return SHOW_MSG_PAGE;
	}
	
	@Action(UPDATE)
	public String update(){
		return null;
	}
	
	@Action("applyodd")
	public String applyodd(){
		applyDate = new Date();
		mark = false;
		StringBuilder names = new StringBuilder();
		 List<Organization> orgs = organizationService.findShopsByCurrentUser();
		 shops = new ArrayList<Shop>();
		 if(orgs != null && orgs.size() > 0){
				for (Iterator<Organization> iterator = orgs.iterator(); iterator.hasNext();) {
					Organization org = iterator.next();
					names.append(org.getName());
					Shop shop = shopService.find(org.getObjectId());
					shops.add(shop);
				}
			}
		return "applyodd";
	}
	/**
	 * 提交申请单
	 * @return
	 */
	@Action("addOne")
	public String addOne(){
		mark = true;
		
		Shop shopad = new Shop();
		shopad.setId(shopId);
		
		ApplyCer aCer = new ApplyCer();
		aCer.setApplyDate(null);
		aCer.setShop(shopad);
		aCer.setUser(getUser());
		aCer.setState(ApplyAddType.NOTSTART);
		
		applyCerService.save(aCer);
		
		applyCer = applyCerService.find(aCer.getId());
		shop = shopService.find(shopId);
		applyDate = applyCer.getApplyDate();
		return "applyodd";
	}
	/**
	 * 审核
	 * @return
	 */
	@Action("auditingApply")
	public String auditingApply(){
		if(mark){//同意
			if(applyIds != null && applyIds.length > 0){
				ApplyCer aCer = applyCerService.find(id);
				List<ApplyCerList> applyCerLists = new ArrayList<ApplyCerList>();
				
				for( int i = 0; i < aCer.getApplyCerLists().size(); i++ ){
					ApplyCerList applyCerList = aCer.getApplyCerLists().get(i);
					for(int j = 0; j < applyIds.length; j++){
						if(applyCerList.getId().equals(applyIds[j])){
							applyCerLists.add(applyCerList);
						}else{
							applyCerList.setState("未通过");
						}
					}
				}
				
				String error = this.valCertificates(applyCerLists);
				if(StringUtils.isNotBlank(error)){
					setFailPopMessage("审核失败:<br/>" + error);
					return SHOW_MSG_PAGE;
				}

				for (Iterator<ApplyCerList> iterator = applyCerLists.iterator(); iterator
						.hasNext();) {
					ApplyCerList applyCerList = iterator.next();
					Certification certification = this.copyCertification(applyCerList);
					applyCerList.setState("已通过");
					certificationService.save(certification);
					
				}
				
				aCer.setState(ApplyAddType.FINISH);
				applyCerService.save(aCer);
				Workflow w= workflowService.find(WorkflowType.ADDLIST, id);
				workflowService.audit(getUser(), w, WorkflowState.PASS, WorkflowOperateType.FINISH, msg);
			}else{
				setFailPopMessage("请勾选至少一个合格证。");
				return SHOW_MSG_PAGE;
			}
			
		}else{//退回
			ApplyCer aCer = applyCerService.find(id);
			for(int i=0;i<aCer.getApplyCerLists().size();i++){
				ApplyCerList applyCerList = aCer.getApplyCerLists().get(i);
				applyCerList.setState("未通过");
			}
			aCer.setState(ApplyAddType.REFUSED);
			applyCerService.save(aCer);
			Workflow w= workflowService.find(WorkflowType.ADDLIST, id);
			workflowService.audit(getUser(), w, WorkflowState.REFUSED, WorkflowOperateType.REFUSE, msg);
		}
		setSuccessPopMessage("更新数据成功");
		
		return SHOW_MSG_PAGE;
	}
	
	private String valCertificates(List<ApplyCerList> applyCerLists) {
		List<ApplyCerList> cerLists = applyCerLists;
		StringBuilder errors = new StringBuilder("");
		for (Iterator<ApplyCerList> iterator = cerLists.iterator(); iterator.hasNext();) {
			ApplyCerList applyCerList =  iterator.next();
			Certification certification = certificationService.findCfByCerNum(applyCerList.getCertificationNum());
			boolean isAddBr = false;
			if(certification != null){
				errors.append("合格证号&lt;" + certification.getCertificationNum() + "&gt;重复、");
				isAddBr = true;
			}
			certification = certificationService.getEntityDao().findUniqueBy("chassis", applyCerList.getChassis());
			if(certification != null){
				errors.append("车架号&lt;" + certification.getChassis() + "&gt;重复.");
			}
			
			if(isAddBr) {
				errors.append("<br/>");
			}
		}
		
		return errors.toString();
	}

	@Resource
	private CommonService commonService;
	
	/**
	 * 提取单条记录
	 */
	@Action("seleteOnApply")
	public String seleteOnApply(){
		mark = true;
		applyCer = applyCerService.find(id);
		shop = shopService.find(shopId);
		applyDate = applyCer.getApplyDate();
		System.out.println(applyCer.getApplyCerLists().size());
		return "applyodd";
	}
	/**
	 * 添加合格证信息
	 * @return
	 */
	@Action("oPenAddTwo")
	public String oPenAddTwo(){
		shop = shopService.find(shopId);
		
		cerF = new ApplyCerList();
		cerF.setBulvDate(DateUtil.getDate());
		cerF.setScheduledDate(DateUtil.getDate());
		return ADD;
	}
	/**
	 * 详情页面加载
	 * @return
	 */
	@Action("checkApplyodd")
	public String checkApplyodd(){
		applyCer = applyCerService.find(id);
		shop = shopService.find(applyCer.getShop().getId());
		applyDate = applyCer.getApplyDate();
		return "checkApplyodd";
	}
	/**
	 * 审核页面加载
	 * @return
	 */
	@Action("auditingApplyodd")
	public String auditingApplyodd(){
		applyCer = applyCerService.find(id);
		shop = shopService.find(applyCer.getShop().getId());
		applyDate = applyCer.getApplyDate();
		setRedirectUrl("index.do?currentPage="+getCurrentPage(),"applyCerDTO",applyCerDTO);
		return "auditingApplyodd";
	}
	/**
	 * 审核页面加载
	 * @return
	 */
	@Action("toDetail")
	public String toDetail(){
		cerF = applyCerListService.find(id);
		applyCer = applyCerService.find(cerF.getApplyCer().getId());
		shop = shopService.find(applyCer.getShop().getId());
		applyDate = applyCer.getApplyDate();
		return "detail";
	}
	
	@Action("updateTwo")
	public String updateTwo(){
		Shop shop = new Shop();
		shop.setId(shopId);
		cerF.setFinancial(getFinancial());
		cerF.setShop(shop);
		cerF.setState("未审核");// 合格证状态，此为未完成的状态，
//		cerF.setBulvDate(new Date());
		cerF.setApplyCer(applyCer);
		if(!StringUtils.isNotBlank(cerF.getCertificationNum()))
				cerF.setCertificationNum(null);
		applyCerListService.save(cerF);
		
		setSuccessPopMessage("保存数据成功");
		setRedirectUrl("seleteOnApply.do?id="+applyCer.getId()+"&shopId="+shopId);
		return SHOW_MSG_PAGE;
	}
	
	@Action("addTwo")
	public String addTwo(){
		ApplyCer applyCer = new ApplyCer();
		applyCer.setId(id);
		Shop shop = new Shop();
		shop.setId(shopId);
		cerF.setFinancial(getFinancial());
		cerF.setShop(shop);
//		cerF.setCmImporting(CopyOfCertificationImporting.NO);// 导入标记
		cerF.setState("未审核");// 合格证状态，此为未完成的状态，
//		cerF.setBulvDate(new Date());
		cerF.setApplyCer(applyCer);
		if(!StringUtils.isNotBlank(cerF.getCertificationNum()))
				cerF.setCertificationNum(null);
		applyCerListService.save(cerF);
		
		setSuccessPopMessage("保存数据成功");
		setRedirectUrl("seleteOnApply.do?id="+id+"&shopId="+shopId);
		return SHOW_MSG_PAGE;
	}
	/**
	 * 删除单条记录
	 */
	@Action("deleteapplyCerList")
	public String deleteapplyCerList(){
		applyCerListService.destory(applyCerListid);
		setSuccessPopMessage("删除数据成功");
		setRedirectUrl("seleteOnApply.do?id="+id+"&shopId="+shopId);
		return SHOW_MSG_PAGE;
	}
	
	public Certification copyCertification(ApplyCerList applyCerList){
		Certification certification = new Certification();
		
		certification.setShop(applyCerList.getShop());
		certification.setFinancial(applyCerList.getFinancial());
		certification.setBrand(applyCerList.getBrand());
		certification.setCertificationNum(applyCerList.getCertificationNum());
		certification.setDepartDate(applyCerList.getDepartDate());
		certification.setMotorcycleType(applyCerList.getMotorcycleType());
		certification.setChassis(applyCerList.getChassis());
		certification.setEngine(applyCerList.getEngine());
		certification.setOrderNumber(applyCerList.getOrderNumber());
		certification.setSupplyPrice(applyCerList.getSupplyPrice());
		certification.setDraft(applyCerList.getDraft());
		certification.setDraftBeginDate(applyCerList.getDraftBeginDate());
		certification.setDraftEndDate(applyCerList.getDraftEndDate());
		certification.setGoingOutDate(applyCerList.getGoingOutDate());
		certification.setScheduledDate(applyCerList.getScheduledDate());
		certification.setLeaveDate(applyCerList.getLeaveDate());
		certification.setCmImporting(CopyOfCertificationImporting.NO);
		certification.setState(CertificationType.INSTOCK);
		certification.setBuluDate(applyCerList.getBulvDate());
		certification.setWarehouseDate(new Date());
		certification.setCreateDate(new Date());// 添加创建时间
		
		return certification;
	}
	
	
	
	public Date getApplyDate() {
		return applyDate;
	}
	public void setApplyDate(Date applyDate) {
		this.applyDate = applyDate;
	}
	public Boolean getMark() {
		return mark;
	}
	public void setMark(Boolean mark) {
		this.mark = mark;
	}
	public List<Shop> getShops() {
		return shops;
	}
	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}
	public Long getShopId() {
		return shopId;
	}
	public void setShopId(Long shopId) {
		this.shopId = shopId;
	}
	public ApplyCer getApplyCer() {
		return applyCer;
	}
	public void setApplyCer(ApplyCer applyCer) {
		this.applyCer = applyCer;
	}
	public Shop getShop() {
		return shop;
	}
	public void setShop(Shop shop) {
		this.shop = shop;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	public ApplyCerList getCerF() {
		return cerF;
	}
	public void setCerF(ApplyCerList cerF) {
		this.cerF = cerF;
	}
	public Financial getFinancial() {
		return financial;
	}
	public void setFinancial(Financial financial) {
		this.financial = financial;
	}
	public Long getApplyCerListid() {
		return applyCerListid;
	}
	public void setApplyCerListid(Long applyCerListid) {
		this.applyCerListid = applyCerListid;
	}
	public ApplyCerDTO getApplyCerDTO() {
		return applyCerDTO;
	}
	public void setApplyCerDTO(ApplyCerDTO applyCerDTO) {
		this.applyCerDTO = applyCerDTO;
	}
	public String getShopName() {
		return shopName;
	}
	public void setShopName(String shopName) {
		this.shopName = shopName;
	}
	public Long[] getApplyIds() {
		return applyIds;
	}
	public void setApplyIds(Long[] applyIds) {
		this.applyIds = applyIds;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	

}
